package com.dzy.boot.lock.core;

import com.dzy.boot.lock.annotation.DLock;
import com.dzy.boot.lock.factory.LockFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dzy.boot.lock.factory.Lock;

@Aspect
@Component
public class DLockAspectHandler {

    @Autowired
    LockFactory lockFactory;
    
    @Around("@annotation(dLock)")
    public Object around(ProceedingJoinPoint joinPoint, DLock dLock) throws Throwable {
        Lock lock = lockFactory.getLock(joinPoint, dLock);
        boolean currentThreadLock = false;
        try {
            currentThreadLock = lock.acquire();
            return joinPoint.proceed();
        } finally {
            if (currentThreadLock) {
                lock.release();
            }
        }
    }
}
